<?php

namespace Simanx\Spes\Loader;

use Simanx\Spes\Attribute\ClassAttributeProxy;
use Simanx\Spes\Attribute\Event\Attributes\Listen;
use Simanx\Spes\Providers\EventServiceProvider;

/**
 * 事件Attribute加载器
 * @package Simanx\Spes\Event
 */
class EventLoader extends Loader
{
    public function load()
    {
        if ($this->app->eventsAreCached()) {
            return;
        }

        $events = $this->getEvents();
        /** @var EventServiceProvider $eventServiceProvider */
        $eventServiceProvider = $this->app->getProvider(EventServiceProvider::class);
        $eventServiceProvider->load($events);
    }

    public function getEvents()
    {
        $classNames = $this->classes();
        $events = [];
        foreach ($classNames as $className) {
            $classAttrProxy = ClassAttributeProxy::create($className);
            $listenAttrs = $classAttrProxy->getAttributes(Listen::class);
            if (!$listenAttrs) {
                return [];
            }

            /** @var Listen $listenAttr */
            foreach ($listenAttrs as $listenAttr) {
                foreach ($listenAttr->events as $event) {
                    $events[] = [
                        'event'    => $event,
                        'listener' => $className,
                        'priority' => $listenAttr->getPriority($event)
                    ];
                }
            }
        }

        uksort($events, function ($a, $b) {
            if ($a['priority'] == $b['priority']) {
                return 0;
            }

            return $b['priority'] - $a['priority'];
        });

        return $events;
    }
}